<template>
  <div class="app-container calendar-list-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <span style="color:gray; font-size:13px">抽奖时间: </span>
      <el-date-picker clearable v-model="timeInterval" style="width: 500px" type="daterange" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
      </el-date-picker>

      <el-select size="mini" v-model="listQuery.sendFlag" clearable placeholder="抽奖结果">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>

      <el-button class="filter-item" style="margin-top: 10px;margin-left: 47px" type="primary" size="mini" icon="el-icon-search" @click="getList">查找</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table size="small" :data="list" v-loading="listLoading" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <el-table-column align="center" label="用户ID" prop="userId">
      </el-table-column>

      <el-table-column align="center" label="抽奖时间" prop="drawTime">
      </el-table-column>

      <el-table-column align="center" label="中奖奖品ID" prop="awardId">
      </el-table-column>

      <el-table-column align="center" label="中奖时间" prop="createTime">
      </el-table-column>

      <el-table-column align="center" label="中奖用户" prop="userName">
      </el-table-column>

      <el-table-column align="center" label="中奖名称" prop="awardName">
      </el-table-column>

      <el-table-column align="center" label="积分价值" prop="integral">
      </el-table-column>

      <el-table-column align="center" label="发放标志" prop="sendFlag">
        <template slot-scope="scope">
          <el-tag>{{handleType[scope.row.sendFlag]}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" min-width="80" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-dropdown>
            <el-button type="warning" size="mini">
              操作
              <i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-button type="primary" size="mini" plain @click="handleSend(scope.row)" v-if="scope.row.sendFlag==1">发 放</el-button>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog title="发货" :visible.sync="shipDialogVisible" width="600px">
      <el-form ref="shipForm" :model="shipForm" status-icon label-position="left" label-width="100px" style='width: 400px; margin-left:50px;'>

        <el-form-item label="订单编号" prop="shipForm.orderCode">
          <span>{{shipForm.orderCode}}</span>
        </el-form-item>
        <el-form-item label="商品名称" prop="shipForm.goodsName">
          <span>{{ shipForm.goodsName }}</span>
        </el-form-item>
        <el-form-item label="收货人" prop="shipForm.receiverName">
          <span>{{ shipForm.receiverName }}</span>
        </el-form-item>
        <el-form-item label="手机" prop="shipForm.receiverMobile">
          <span>{{ shipForm.receiverMobile }}</span>
        </el-form-item>
        <el-form-item label="收件人地址" prop="shipForm.receiverAddress">
          <span>{{ shipForm.receiverAddress }}</span>
        </el-form-item>
        <el-form-item label="发货方" prop="shipper">
          <el-select v-model="shipForm.shipper">
            <el-option label="爱能" value="0" :selected="true"></el-option>
            <el-option label="其他仓库" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="快递公司" prop="shipperCode" v-show="shipForm.shipper == '0'">
          <el-select v-model="shipForm.shipperCode" placeholder="请选择快递公司">
            <el-option label="顺丰速运" value="SF" :selected="true"></el-option>
            <!-- <el-option label="中通快递" value="ZTO"></el-option> -->
            <el-option label="圆通速递" value="YTO"></el-option>
            <el-option label="邮政快递包裹" value="YZPY"></el-option>
            <el-option label="邮政国内标快" value="YZBK"></el-option>
            <!-- <el-option label="韵达速递" value="YD"></el-option> -->
            <!-- <el-option label="EMS" value="EMS"></el-option> -->
            <!-- <el-option label="德邦快递" value="DBL"></el-option> -->
            <!-- <el-option label="宅急送" value="ZJS"></el-option> -->
            <!-- <el-option label="TNT快递" value="TNT"></el-option> -->
          </el-select>
        </el-form-item>
        <el-form-item label="邮费支付方式" prop="payType" v-show="shipForm.shipper == '0'">
          <el-select v-model="shipForm.payType" placeholder="请选邮费支付方式">
            <el-option label="现付" value="1"></el-option>
            <el-option label="到付" value="2"></el-option>
            <el-option label="月结" value="3"></el-option>
            <el-option label="第三方支付" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="快递类型" prop="expType" v-show="shipForm.shipper == '0'">
          <el-select v-model="shipForm.expType" placeholder="请选快递类型">
            <el-option label="标准快件" value="1"></el-option>
            <el-option label="顺丰特惠" value="2"></el-option>
            <el-option label="顺丰物流普运" value="13"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="子母件个数" prop="quantity" v-show="shipForm.shipper == '0'">
          <el-input-number v-model="shipForm.quantity" placeholder="1" :min="1">
            <!-- <template slot="append">分</template> -->
          </el-input-number>
        </el-form-item>
        <el-form-item label="物流单号" prop="shipSn" v-show="(shipForm.shipperCode == 'YTO' && shipForm.payType == 2) || shipForm.shipper == '1'">
          <el-input ref="content" v-model.trim="shipForm.shipSn"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="shipDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="generateElectronicSurface" v-show="shipForm.shipper == '0'">生成电子面单</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>

<script>
import { lotteryList, sendAward, getAddress } from '@/api/lotteryRecord'
import { generateSurface } from '@/api/express'

export default {
  name: 'report',
  data() {
    return {
      handleType: ['未中奖', '未发奖', '已发奖'],
      options: [
        {
          value: '0',
          label: '未中奖'
        },
        {
          value: '1',
          label: '未发奖'
        },
        {
          value: '2',
          label: '已发奖'
        }
      ],
      value: '',
      LODOP: '',
      downloadLoading: false,
      timeInterval: null,
      listQuery: {
        page: 1,
        limit: 20,
        sendFlag: undefined,
        sort: '+id'
      },
      shipDialogVisible: false,
      lotteryId: undefined,
      shipForm: {
        receiverName: undefined,
        receiverId: undefined,
        receiverMobile: undefined,
        receiverProvinceName: undefined,
        receiverCityName: undefined,
        receiverExpAreaName: undefined,
        receiverAddress: undefined,
        goodsName: undefined,
        orderCode: undefined,
        shipper: '0',
        shipperCode: 'SF',
        payType: '1',
        expType: '2',
        quantity: '1',
        lottery: '1'
      },
      list: null,
      total: undefined,
      listLoading: true
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      if (this.timeInterval != null) {
        this.listQuery.start = this.timeInterval[0]
        this.listQuery.end = this.timeInterval[1]
      } else {
        this.listQuery.start = ''
        this.listQuery.end = ''
      }
      lotteryList(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleSend(row) {
      var noiseChar = '#$%^&_+-=`[]{};\':"\\|,./<>?\n\r～！＠＃＄％＆＊·‘’¥——＿＋－＝｀｛｝；＇：＂＼｜，．／“”　'
      var goodChar = ''
      getAddress({ id: row.userId })
        .then(response => {
          // this.orderDetail = response.data.data
          this.shipForm.receiverName = response.data.data.litemallAddress.name
          this.shipForm.receiverId = row.userId
          this.shipForm.receiverMobile = response.data.data.litemallAddress.mobile
          this.shipForm.receiverAddress = response.data.data.detailAddress
          this.shipForm.orderCode = response.data.data.createSns
          this.shipForm.goodsName = row.awardName
          for (var i = 0; i < noiseChar.length; i++) {
            var oneChar = noiseChar.charAt(i)
            var towChar = goodChar
            this.shipForm.goodsName = this.shipForm.goodsName.replace(oneChar, towChar)
          }

          this.shipDialogVisible = true
          this.lotteryId = row.id
          this.$nextTick(() => {
            this.$refs['shipForm'].clearValidate()
          })

          this.$notify({
            title: '成功',
            message: '操作成功',
            type: 'success',
            duration: 2000
          })
        })
        .catch(res => {
          this.$notify({
            title: '失败',
            message: res.data.errmsg,
            type: 'error',
            duration: 2000
          })
        })
    },

    generateElectronicSurface() {
      if (this.shipForm.shipperCode === 'YTO' && this.shipForm.payType === '2') {
        if (this.shipForm.shipSn === null || this.shipForm.shipSn === '' || this.shipForm.shipSn === undefined) {
          this.$message.info('物流单号不能为空')
          this.$refs.content.focus()
        } else {
          const loading = this.$loading({
            lock: true,
            text: '正在生成电子面单',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          this.shipDialogVisible = false
          generateSurface(this.shipForm).then(response => {
            loading.close()
            this.getList()
            var data = response.data
            if (data.errno === 0) {
              this.$notify({
                title: '成功',
                message: '发货成功',
                type: 'success'
              })
              var jsondata = JSON.parse(data.data)
              var newWindow = window.open('', '_blank')
              newWindow.document.write(jsondata['PrintTemplate'])
              setTimeout(() => {
                newWindow.print()
              }, 100)
            } else {
              this.$notify({
                title: '失败',
                message: '发货失败，请重试',
                type: 'error'
                // duration: 2000
              })
            }
          })
          // setTimeout(() => {
          //   loading.close()
          // }, 2000)
        }
      } else {
        const loading = this.$loading({
          lock: true,
          text: '正在生成电子面单',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.shipDialogVisible = false
        generateSurface(this.shipForm).then(response => {
          loading.close()
          this.getList()
          var data = response.data
          if (data.errno === 0) {
            this.$notify({
              title: '成功',
              message: '发货成功',
              type: 'success'
            })
            // 修改抽奖状态
            sendAward({ id: this.lotteryId }).then(res => {})
            var jsondata = JSON.parse(data.data)
            if (jsondata.SubCount > 0) {
              var newWindows = window.open('', '_blank')
              newWindows.document.write(jsondata['PrintTemplate'])
              newWindows.document.writeln("<span style='line-height:2px;'></span><br><br>")
              for (var i = 0; i < jsondata.SubCount; i++) {
                newWindows.document.write(jsondata.SubPrintTemplates[i])
                newWindows.document.writeln("<span style='line-height:2px;'></span><br><br>")
              }
              setTimeout(() => {
                newWindows.print()
              }, 200)
            } else {
              var newWindow = window.open('', '_blank')
              newWindow.document.write(jsondata['PrintTemplate'])
              setTimeout(() => {
                var LODOP = /*global getLodop*/ /*eslint no-undef: "error"*/ getLodop()
                // LODOP.PRINT_INITA(10, 10, 754, 453, '打印控件功能演示_Lodop功能_多页文档')
                LODOP.SET_PRINT_STYLEA(2, 'FontSize', 18)
                LODOP.SET_PRINT_STYLEA(2, 'Bold', 1)
                LODOP.ADD_PRINT_HTM(0, 0, '100%', '100%', jsondata['PrintTemplate'])
                var cont = LODOP.GET_PRINTER_COUNT()
                for (var i = 0; i < cont; i++) {
                  var strPrinterName = LODOP.GET_PRINTER_NAME(i)
                  if (strPrinterName === 'HPRT HLP106S') {
                    LODOP.SET_PRINTER_INDEXA(strPrinterName)
                  }
                }
                window.location.reload()
                LODOP.PREVIEW()
              }, 100)
            }
          } else {
            this.$notify({
              title: '失败',
              message: '发货失败，请重试',
              type: 'error'
              // duration: 2000
            })
          }
        })
        // setTimeout(() => {
        //   loading.close()
        // }, 2000)
      }
    },

    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    }
  }
}
</script>
